package com.yuliang.handle.security;

import com.alibaba.fastjson.JSON;
import com.yuliang.domain.R;
import com.yuliang.enums.AppHttpCodeEnum;
import com.yuliang.utils.WebUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {//认证失败处理器

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        e.printStackTrace();//打印异常信息
        //InsufficientAuthenticationException 需要登入才有权限
        //BadCredentialsException 用户名或密码错误或者账号被封
        R result = null;
        if (e instanceof InsufficientAuthenticationException){
            result = R.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        } else if (e instanceof BadCredentialsException) {
            result = R.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(),e.getMessage());
        }else {
            result = R.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),"网络异常，请稍后再试");
        }
        //响应给前端
        WebUtils.renderString(response, JSON.toJSONString(result));
    }
}
